/* Copyright (c) 2004-2022 peigen.info. All rights reserved. */

package info.peigen.hotpot.common.core.util;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import jakarta.validation.*;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * <b>(ValidationUtil)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2021/7/14
 */
@Slf4j
public class ValidationUtil {
    /**
     * 校验参数
     *
     * @param object 被校验对象
     */
    public static void validateParams(Object object) {
        ValidatorFactory                 factory    = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory();
        Validator                        validator  = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        if (violations.size() > 0) {
            List<String> msgList = Lists.newArrayList("\n");
            for (ConstraintViolation<Object> violation : violations) {
                msgList.add(violation.getRootBeanClass().getSimpleName() + "." + violation.getPropertyPath() + ":" + violation.getMessage());
            }
            String message = StrUtil.join("\n", msgList.toArray());
            log.error("参数校验有误:{}", message);
            throw new ConstraintViolationException(message, violations);
        }
    }

    /**
     * 分组校验参数
     *
     * @param object     被校验对象
     * @param groupClass class组
     *
     * @return String
     */
    public static String validateParams(Object object, Class<?>... groupClass) {
        ValidatorFactory                 factory    = Validation.buildDefaultValidatorFactory();
        Validator                        validator  = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(object, groupClass);
        if (violations.size() > 0) {
            List<String> msgList = new ArrayList<>();
            for (ConstraintViolation<Object> violation : violations) {
                msgList.add(violation.getMessage());
            }
            return StrUtil.join(",", msgList.toArray());
        } else {
            return null;
        }
    }
}